package com.sinopec.uhf.chengwei.net

import android.app.Activity
import android.content.Context
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.rscja.deviceapi.RFIDWithUHFA4NetWork
import com.rscja.deviceapi.interfaces.IUHFA4
import com.sinopec.iuhf.IUhfHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.launch

//通过协程来读取 关闭协程 则读取就关闭
class NetLifecycleUhfHelper(
    private val context: Context,
    private val reader: IUHFA4,
    private val ip: String,
    private val port: String,
) : LifecycleEventObserver, IUhfHelper {

    //开始读取
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> {
                source.lifecycleScope.launch(Dispatchers.IO) {
                    (reader as? RFIDWithUHFA4NetWork)?.setIPAndPort(ip, port.toIntOrNull() ?: 0)
                    reader.free()
                    reader.init(context)
                }
            }

            Lifecycle.Event.ON_DESTROY -> {
                reader.free()
            }

            else -> {

            }
        }
    }

    override fun readTags(userOrEpc: (user: String, epc: String) -> String): Flow<String> {
        return NetCoroutineRead.readATag(reader)
            .map {
                if (it == null) {
                    ""
                } else {
                    Log.e("TAG", "readTags: =================${it.user}  ${it.epc}", )
                    userOrEpc(it.user ?: "", it.epc ?: "")
                }
            }.onCompletion {
            }.flowOn(Dispatchers.IO)
    }

}

//从生命周期中获取 uhf控制器 它会自动跟随生命周期的变化向uhf内核发送指令
fun LifecycleOwner.netLifecycleUhfHelper(
    reader: IUHFA4,
    ip: String,
    port: String
): IUhfHelper {
    val helper = NetLifecycleUhfHelper(
        when {
            this is Activity -> this
            else -> error("此处无法获取 上下文 context")
        },
        reader,
        ip,
        port
    )
    lifecycle.addObserver(helper)
    return helper
}